#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "Commn.hpp"
#include "Log.hpp"
#include "Socket.hpp"
#include <memory>
using namespace SocketModule;
using namespace LogModule;
void HandlerRequest(SockPtr ret, InetAddr &client)
{
    while (true)
    {
        std::string message;
        int n = ret->ToRecv(&message);
        if (n > 0)
        {
            LOG(LogLevel::INFO) << client.Info() << "say: " << message;
            std::string retstr = "echo say# " + message;
            ret->ToSend(retstr);
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "写端退出";
            break;
        }
        else
            break;
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage();
    }
    // int n = sizeof(argv) / sizeof(argv[0]);
    // for (int i = 0; i < n; i++){
    //     LOG(LogLevel::INFO) << "命令行参数: " << std::string(argv[i]);
    // }

    // LOG(LogLevel::INFO) << "输入的字符串为: " << std::string(argv[1]);
    uint16_t port = std::stoi(argv[1]);
    // LOG(LogLevel::INFO) << "输入的端口号为: " << port;
    std::shared_ptr<Socket> _tsvr = std::make_shared<TcpSocket>();
    _tsvr->BuildTckSocket(port);
    while (true)
    {
        InetAddr client;
        SockPtr ret = _tsvr->Acceptor(&client);
        HandlerRequest(ret, client);
    }
    return 0;
}